Day12 是要來做偵測鍵盤輸入的彩蛋遊戲
const SECRET_CODE: string = "wesbos";
const [pressedKeys, setPressedKeys] = useState<string[]>([]);
const [showSecret, setShowSecret] = useState<boolean>(false);
const handleKeyUp = useCallback((e: KeyboardEvent<HTMLDivElement>) => {
setPressedKeys((prev: string[]) => {
const updatedKeys: string[] = [...prev, e.key].slice(-SECRET_CODE.length);
if (updatedKeys.join("").includes(SECRET_CODE)) {
setShowSecret(true);
console.log("SECRET CODE ACTIVATED!");
}
return updatedKeys;
});
}, []);
return (
<div
className="flex flex-col items-center justify-center min-h-screen bg-gray-100"
tabIndex={0}
onKeyUp={handleKeyUp}
autoFocus
>
<h1 className="text-3xl font-bold mb-4">Key Sequence Detection</h1>
<p className="text-lg mb-4">Type the secret code: 'wesbos'</p>
<div className="bg-white p-6 rounded-lg shadow-md">
<p className="text-xl mb-2">Pressed keys:</p>
<div className="flex flex-wrap gap-2 mb-4">
{pressedKeys.map((key: string, index: number) => (
<span key={index} className="bg-blue-200 px-2 py-1 rounded">
{key}
</span>
))}
</div>
</div>
{showSecret && (
<div
className="mt-8 bg-green-100 border-l-4 border-green-500 text-green-700 p-4 flex items-center"
role="alert"
>
<p>Secret code activated! You found the easter egg!</p>
</div>
)}
</div>
);
}
https://codesandbox.io/p/devbox/day12-key-sequence-detection-vfvg9j